package com.wenhao.leetcode.hard;

import java.util.ArrayList;
import java.util.List;

/**
 * 问题：https://leetcode-cn.com/problems/n-queens/
 * N皇后
 *
 * 递归的思路
 * 首先写出判断当前排列是否符合题意的方法
 * 使用一个一维数组记录当前的排列
 *
 * 虽然顺利地写出来了但是思路还是有一点不清晰
 *
 * @author Wenhao Tong
 * @Description
 * @create 2021-06-28 12:28
 */
public class LeetCode51 {

    public static void main(String[] args) {
        LeetCode51 leetCode51 = new LeetCode51();
        List<List<String>> lists = leetCode51.solveNQueens(4);
        for (List<String> list : lists) {
            for (String num : list) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }

    public List<List<String>> solveNQueens(int n) {
        int[] queens = new int[n];
        for (int i = 0;i < queens.length;i++) {
            queens[i] = -1;
        }
        solve(0,queens);
        return result;
    }

    List<List<String>> result = new ArrayList<>();

    public String getCode (int length,int position) {
        char[] chars = new char[length];
        for (int i = 0;i < chars.length;i++) {
            chars[i] = '.';
        }
        chars[position] = 'Q';
        return new String(chars);
    }

    public void solve (int index,int[] queens) {
        if (index == queens.length) {
            List<String> list = new ArrayList<>();
            for (int position : queens) {
                list.add(getCode(queens.length,position));
            }
            result.add(list);
            return;
        }
        for (int i = 0;i < queens.length;i++) {
            queens[index] = i;
            if (valid(index,queens)) {
                solve(index + 1,queens);
            }
        }
    }

    public boolean valid(int index,int[] queens) {
        for (int i = 0;i <= index;i++) {
            for (int j = i + 1;j <= index;j++) {
                if (queens[i] == queens[j]) {
                    return false;
                }
                if (queens[i] - queens[j] == i - j || queens[i] - queens[j] == j - i) {
                    return false;
                }
            }
        }
        return true;
    }
}
